package com.art.coconut.service.impl;

import com.art.coconut.change.ChangePojo;
import com.art.coconut.change.PropertyProcessPojo;
import com.art.coconut.core.Coconut;
import com.art.coconut.enums.ChangeTypeEnum;
import com.art.coconut.enums.PropertyTypeEnum;
import com.art.coconut.service.IPropertyProcess;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class ListProcess implements IPropertyProcess {
    @Override
    public int processObject(PropertyProcessPojo processPojo, ChangePojo changePojo) throws InstantiationException, IllegalAccessException {
        if(processPojo.getTypePojo().getTypeName().equals(PropertyTypeEnum.LIST_TYPE.getTypeName())){
            Collection<?> left = processPojo.getOld()==null? Collections.EMPTY_LIST:  (Collection<?>) processPojo.getOld();
            Collection<?> right = processPojo.getCurr()==null? Collections.EMPTY_LIST:  (Collection<?>) processPojo.getCurr();
            List<ChangePojo> changePojoList = Coconut.compareCollectionWithDepth(left, right, processPojo.getDepth()+1);
            changePojo.setCollectionFlag(true);
            changePojo.setPropertyChangeList(changePojoList);
            List<ChangePojo> modifyList = changePojoList
                    .stream()
                    .filter(b-> b.getChangeType().equals(ChangeTypeEnum.MODIFIED)
                            || b.getChangeType().equals(ChangeTypeEnum.ADDED)
                            || b.getChangeType().equals(ChangeTypeEnum.REMOVED)
                    )
                    .collect(Collectors.toList());
            if(!modifyList.isEmpty()){
                return 1;
            }
        }
        return 0;
    }
}
